<script lang="ts" setup>
import type { FieldRule, FormInstance } from '@arco-design/web-vue'
import type { AcmeCreateParams } from '@/apis/model/License'
import { Message } from '@arco-design/web-vue'
// import { getApiResolveDomainsApi } from '@/apis/modules/resolve/domain'

import { updateCertAcmeApi } from '@/apis/modules/cert'
// import { addApiAcmeAccountApi } from '@/apis/modules/license'
import {
  LicenseAlgorithmOptions,
  LicenseBrandOptions,
} from '@/constants/cdn-node'

const emit = defineEmits(['reload'])
const visible = defineModel<boolean>('visible', { required: true })
const formRef = ref<FormInstance>()
const formState = reactive<AcmeCreateParams>({
  email: '',
  algorithm: 'EC256',
  brand: 'Let\'s Encrypt',
})
const rules: Record<string, FieldRule> = {
  email: {
    required: true,
    validator(value, callback) {
      if (!value) {
        return callback('请输入账户邮箱')
      }
      if (!regexpMap.email.test(value)) {
        return callback('邮箱格式不正确')
      }
      callback()
    },
  },
  brand: { required: true, message: '请选择证书品牌' },
  algorithm: { required: true, message: '请选择密钥算法' },
}
async function handleSubmit() {
  const error = await formRef.value?.validate()
  if (error)
    return false
  return updateCertAcmeApi(formState).then(() => {
    Message.success('操作成功')
    emit('reload')
  })
}
function handleClose() {
  formRef.value?.resetFields()
}
</script>

<template>
  <resource-dialog
    v-model:visible="visible"
    title="新建 ACME 账户"
    :width="480"
    :mask-closable="false"
    :before-ok="handleSubmit"
    :before-close="handleClose"
  >
    <a-form
      ref="formRef"
      layout="vertical"
      :model="formState"
      :rules="rules"
    >
      <a-form-item
        label="账户邮箱"
        field="email"
        asterisk-position="end"
      >
        <a-input
          v-model="formState.email"
          :max-length="64"
          show-word-limit
          placeholder="请输入账户邮箱"
        />
      </a-form-item>
      <a-form-item
        label="账户品牌"
        field="brand"
        asterisk-position="end"
      >
        <a-select
          v-model="formState.brand"
          :options="LicenseBrandOptions"
          placeholder="请选择账户品牌"
        />
      </a-form-item>
      <a-form-item
        label="密钥算法"
        field="algorithm"
        asterisk-position="end"
      >
        <a-select
          v-model="formState.algorithm"
          placeholder="请选择密钥算法"
          :options="LicenseAlgorithmOptions"
        />
      </a-form-item>
    </a-form>
  </resource-dialog>
</template>
